package com.sensetime.bi.senselink.server.rtsptest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.SocketException;
import java.util.TimerTask;

/**
 * Task that gets invoked after every 20 msec
 */
public class RtpPkgProcess extends TimerTask {
    private RtspCtl ctl;

    RtpPkgProcess(RtspCtl ctl) {
        this.ctl = ctl;
    }

    @Override
    // Every 20 seconds, read from the socket connection
    public void run() {
        // Construct a DatagramPacket
        ctl.rcvdp = new DatagramPacket(ctl.buf, ctl.buf.length);

        try {
            // Receive the data
            if (!ctl.RTPsocket.isClosed()) {
                ctl.RTPsocket.receive(ctl.rcvdp);

                byte[] data = ctl.rcvdp.getData();
                int length = ctl.rcvdp.getLength();
                System.out.println("Data Received: ");

                // Print out its length
                System.out.println("Length of data: " + length);

                // Print the data itself
                System.out.println("Data: ");
                String hexChars = bytesToHex(data, length);
                System.out.println(hexChars);
//                System.exit(0);
            }
        } catch (SocketException se) { // We need to catch here if we decide to invoke TEARDOWN
            // while we are waiting for data coming from the DatagramSocket
            System.out.println("Socket connection closed");
            this.cancel();
        }
        catch (IOException e) {
            System.out.println("Could not read from socket");
            e.printStackTrace();
            this.cancel();
            return;
        }
    }

    // Convenience method to convert a byte array into a string
    // Source: http://stackoverflow.com/a/9855338/3250829
    // Tests shown to be the fastest conversion routine available
    // beating all other built-in ones in the Java API

    // For our byte to hex conversion routine
    final char[] hexArray = "0123456789ABCDEF".toCharArray();

    private String bytesToHex(byte[] bytes, int length) {
        char[] hexChars = new char[length * 2];
        for ( int j = 0; j < length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}
